package cn.com.dingtek.genius.manager.server.web.controller;

import cn.com.dingtek.genius.manager.server.event.LoginEvent;
import cn.com.dingtek.genius.manager.server.repository.db.entity.UserBase;
import cn.com.dingtek.genius.manager.server.service.ProfileService;
import cn.com.dingtek.genius.manager.server.support.sam.Authenticator;
import cn.com.dingtek.genius.manager.server.support.sam.SamToken;
import cn.com.dingtek.genius.manager.server.support.sam.SecurityContextHolder;
import cn.com.dingtek.genius.manager.server.support.sam.annotation.AssertAuth;
import cn.com.dingtek.genius.manager.server.utils.IPUtil;
import cn.com.dingtek.genius.manager.server.utils.UserAgentParser;
import cn.com.dingtek.genius.manager.server.web.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/profile")
public class ProfileController {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private ProfileService profileService;

    @PostMapping("/login")
    public Result login(@RequestBody JSONObject loginForm, HttpServletRequest request, HttpServletResponse response) {
        String account = loginForm.getString("account");
        String passwd = loginForm.getString("passwd");

        String userAgent = request.getHeader("user-agent");

        Long userId = 0L;
        try {
            userId = profileService.verifyLogin(account, passwd);

            SamToken samToken = new SamToken();
            samToken.setUserId(userId);
            samToken.setAccount(account);
            samToken.setCreateTime(System.currentTimeMillis());
            Authenticator.tokenToCookie(request, response, samToken);


            applicationEventPublisher.publishEvent(new LoginEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setIp(IPUtil.getIpAddress(request))
                    .setAgent(UserAgentParser.getBrowser(userAgent))
                    .setOs(UserAgentParser.getOS(userAgent))
                    .setLogState(true)
                    .setRemark("登录成功"));
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(
                    new LoginEvent(this)
                            .setUserId(userId)
                            .setAccountName(account)
                            .setIp(IPUtil.getIpAddress(request))
                            .setAgent(UserAgentParser.getBrowser(userAgent))
                            .setOs(UserAgentParser.getOS(userAgent))
                            .setLogState(false)
                            .setRemark(e.getMessage())
            );
            throw e;
        }

        return Result.ok();
    }

    @AssertAuth
    @GetMapping("/info")
    public Result info() {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        UserBase userBase = profileService.info(userId);
        return Result.ok(new JSONObject()
                .fluentPut("account_name", userBase.getAccountName())
                .fluentPut("real_name", userBase.getAccountName()));
    }

    @AssertAuth
    @PostMapping("/repasswd")
    public Result repasswd(@RequestBody JSONObject loginForm) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();

        String oldPasswd = loginForm.getString("old_passwd");
        String newpasswd = loginForm.getString("new_passwd");
        profileService.repasswd(userId, oldPasswd, newpasswd);
        return Result.ok();
    }
}
